#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>

int main()
{
    int sockfd = socket(AF_INET , SOCK_STREAM , 0);
    if(sockfd < 0)
    {
        std:: cout << "socket error" << std::endl;
        return -1;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    addr.sin_port = htons(8880);
    int ret = bind(sockfd , (sockaddr*)&addr , sizeof(sockaddr_in));
    if(ret < 0)
    {
        perror("bind error");
        return -1;
    }
    ret = listen(sockfd , 10);
    if(ret < 0)
    {
        perror("bind error");
        return -1;
    }
    while(1)
    {
        sockaddr_in client ; 
        socklen_t len = sizeof(client);
        int fd = accept(sockfd , (sockaddr*)&client , &len);
        if(fd < 0)
        {
            perror("accept error");
            return -1;
        }
        char buffer[1024] = {0};

        int ret = recv(fd, buffer,1023, 0);
        if(ret < 0 )
        {
            perror("recv error");
            return -1;
        }else if (ret == 0) {
            perror("peer shutdown!");
            close(fd);
            continue;
        }
        
        std::string body = "<html><body><h1>Hello World</h1></body></html>";
        std::string rsp = "HTTP/1.1 200 OK\r\n";
        rsp += "Content-Length: " + std::to_string(body.size()) + "\r\n";
        rsp += "Content-Type: text/html\r\n";
        rsp += "\r\n";
        rsp += body;

        ret = send(fd, rsp.c_str(), rsp.size(), 0);
        if (ret < 0) {
            perror("send error!");
            close(fd);
            continue;
        }
        close(fd);
    }
    close(sockfd);
    return 0;
}